package gonz;

import gonz.common.config.Config;
import gonz.common.config.GrabLink;
import gonz.grabber.Grabber;
import gonz.grabber.GrabberFactory;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.firefox.internal.ProfilesIni;

import java.util.List;
import java.util.concurrent.TimeUnit;

public class Main {
    public static final Logger LOGGER = Logger.getLogger(Main.class);

    public static void main(String[] args) {
        WebDriver webDriver = null;
        try {
            LOGGER.info("Start.");
            webDriver = setUpWebDriver();

            List<GrabLink> grabLinkList = Config.GRAB_LINKS.getGrabLinks();

            for (GrabLink grabLink : grabLinkList) {
                LOGGER.info("Grab link: " + grabLink);
                Grabber grabber = GrabberFactory.getGrabber(grabLink.getType().toUpperCase());
                grabber.grab(webDriver, grabLink);

            }

            LOGGER.info("End.");
        } catch (Exception e) {
            LOGGER.error("Finished with error.", e);
        } finally {
            tearDownWebDriver(webDriver);
        }

    }

    public static WebDriver setUpWebDriver() {
        ProfilesIni allProfiles = new ProfilesIni();
        FirefoxProfile profile = allProfiles.getProfile("Selenium");
        WebDriver webDriver = new FirefoxDriver(profile);

        String implicitlyWaitUnitStr = Config.SETTINGS.getImplicitlyWaitUnit();
        long implicitlyWait = Config.SETTINGS.getImplicitlyWait();
        if (StringUtils.isNotEmpty(implicitlyWaitUnitStr) && implicitlyWait != 0) {
            TimeUnit implicitlyWaitUnit = TimeUnit.valueOf(implicitlyWaitUnitStr.toUpperCase());
            webDriver.manage().timeouts().implicitlyWait(implicitlyWait, implicitlyWaitUnit);
        }
        return webDriver;
    }

    public static void tearDownWebDriver(WebDriver driver) {
        if (driver != null) {
            driver.close();
        }
    }
}
